﻿package middleware

import (
    "net/http"
    "strings"

    "github.com/gin-gonic/gin"

    "github.com/samaa/photosalesplus/backend/internal/handlers"
    "github.com/samaa/photosalesplus/backend/internal/services"
)

type AuthMiddleware struct {
    service services.AuthService
}

func NewAuthMiddleware(service services.AuthService) *AuthMiddleware {
    return &AuthMiddleware{service: service}
}

func (m *AuthMiddleware) Handle(c *gin.Context) {
    authHeader := c.GetHeader("Authorization")
    if authHeader == "" {
        c.AbortWithStatusJSON(http.StatusUnauthorized, handlers.APIResponse{Error: "未授权"})
        return
    }

    parts := strings.SplitN(authHeader, " ", 2)
    if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
        c.AbortWithStatusJSON(http.StatusUnauthorized, handlers.APIResponse{Error: "无效的凭证"})
        return
    }

    token := strings.TrimSpace(parts[1])
    userID, ok := m.service.Validate(c.Request.Context(), token)
    if !ok {
        c.AbortWithStatusJSON(http.StatusUnauthorized, handlers.APIResponse{Error: "凭证已失效"})
        return
    }

    c.Set("token", token)
    c.Set("user_id", userID)
    c.Next()
}
